// Create an object with an "observe" method for watching download events.
var ft_dl_finished_observer = {
	observe: function(subject, topic, state){
		var file = subject.QueryInterface(Components.interfaces.nsIDownload).targetFile;
		if(file.path.match(/\.torrent$/i)) ft_handle_torrent(file.path);
	}
}

// Add it as a listener to the download manager window.
var ft_os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
ft_os.addObserver(ft_dl_finished_observer, "dl-done",   false);

// Schedule our listener to be removed when the window closes.
window.addEventListener("unload", function(){
	ft_os.removeObserver(ft_dl_finished_observer, "dl-done");
}, false);

// Wait 50ms and check to see if there was a completed file added to the download manager. We have to do this in case
// the torrent finished downloading before the window opened and registered our event handlers, in which case we would
// have missed the 'done' event. This breaks if we try to do it immediately, presumably because the UI hasn't had time
// to initialize itself completely.
setTimeout(function(){
	var dlview = document.getElementById("downloadView");
	if(dlview && dlview.selectedItem && dlview.selectedItem.id.match(/\.torrent/i)){
		ft_handle_torrent(dlview.selectedItem.id.replace(/^file:\/\//i, ""));
	}
}, 50);

// Run this after successfully downloading a torrent file.
function ft_handle_torrent(tPath){
	
	// Add the torrent to FoxTorrent.
	ft_send_message("http://127.0.0.1:9421/api?cid=2&function=downloadFile&r=" + Math.random() + "&url=file://" + tPath);
	
	// Open the FoxTorrent downloads window.
	ft_openui();
	
	// remove the entry from the download manager.
	var e = document.createEvent("Events");
	e.initEvent("download-remove", true, true); 
	document.getElementById("downloadView").selectedItem.dispatchEvent(e);
	
	// Make sure it's gone before we close the window. If not, it will cause problems next time the window is opened.
	ft_wait_for_removed(document.getElementById("downloadView"));
}

function ft_wait_for_removed(el){
	if(el && el.selectedItem) setTimeout(function(){ft_wait_for_removed(el)}, 20);
	else window.close();
}